/*
 * @Author: chengjiang
 * @Date: 2025-07-25 11:52:34
 * @Description: 服务注册发现
 */
package server

import (
	"log"

	"com.damai.services/user/internal/conf"
	"github.com/go-kratos/kratos/contrib/registry/consul/v2"
	"github.com/hashicorp/consul/api"
)

func NewConsulRegistry(c *conf.Server) *consul.Registry {
	client := newConsultClient(c)
	registration := &api.AgentServiceRegistration{
		ID:      "micro-user-service-http",
		Name:    "micro-user-service",
		Port:    8082, // HTTP端口
		Address: "192.168.123.187",
		Tags:    []string{"http"}, // 关键标签
		Check: &api.AgentServiceCheck{
			HTTP:     "http://192.168.123.187:8082/health",
			Interval: "5s",
		},
	}

	err := client.Agent().ServiceRegister(registration)
	if err != nil {
		log.Fatal(err)
	}
	return consul.New(client)
}

func newConsultClient(c *conf.Server) *api.Client {
	client, err := api.NewClient(&api.Config{
		Address: c.Registry.Consul.Address,
		Scheme:  c.Registry.Consul.Scheme,
	})
	if err != nil {
		panic(err)
	}
	return client
}
